import numpy as np


def target_all(x, mat, args):
    if len(x.shape) == 1:
        x0 = x.reshape(1, -1).copy()
    else:
        x0 = x.copy()
    mean_mat = np.mean(mat, -1)
    x0[:, :-1] = x0[:, :-1] / np.sum(x0[:, :-1], axis=-1, keepdims=True)

    sim_val = x0[:, :-1] @ mat
    var = x0[:, -1] * (np.max(sim_val, -1) - np.min(sim_val, -1)) + np.min(sim_val, -1)
    var = var.reshape(-1, 1)
    cvar = var + np.mean(np.maximum(0, sim_val - var), -1, keepdims=True) / (1 - args.a)
    sim_val = np.mean(sim_val, -1, keepdims=True)
    if args.limit_E >= 0:
        sel = (args.limit_E > sim_val)
        ans = sel * (args.limit_E - sim_val) + (~sel) * cvar + sel * 1
    elif args.limit_V is not None:
        sel = (args.limit_V < cvar)
        ans = sel * (- args.limit_V + cvar) + (~sel) * (-sim_val) + sel * 1
    else:
        assert False, "lmt_E and lmt_V cannot be None at the same time"
    return ans
